import { Logger } from '../log'

export async function copy(text: string) {
  function fallbackCopy(text: string) {
    // 弹窗下复制存在的问题,所以使用弹窗下的input来复制
    const target = document.querySelector('div[role="dialog"]') || document.body
    const agent = document.createElement('input')
    target.appendChild(agent)
    agent.value = text
    agent.focus()
    agent.select()
    document.execCommand('copy')
    agent.blur()
    target.removeChild(agent)
  }

  if ('clipboard' in navigator) {
    try {
      await navigator.clipboard.writeText(text)
    } catch (e) {
      Logger.error('clipboard复制失败,将使用降级复制', e as Error)
      fallbackCopy(text)
    }
  } else {
    fallbackCopy(text)
  }
}
